import React from "react";
// import { message } from "antd";
import { connect } from "dva";
import { localUrl } from "../../utils/index";

// function getBase64(img, callback) {
//   const reader = new FileReader();
//   reader.addEventListener("load", () => callback(reader.result));
//   reader.readAsDataURL(img);
// }

// function beforeUpload(file) {
//   const isJPG = file.type === "image/jpeg";
//   const isPNG = file.type === "image/png";
//   if (!isJPG && !isPNG) {
//     message.error("只能上传jpg/png格式图片");
//     return false;
//   }
//   const isLt2M = file.size / 1024 / 1024 < 2;
//   if (!isLt2M) {
//     message.error("图片大小不能超过2M");
//     return false;
//   }
//   return true;
// }

@connect(({ add }) => ({
  add: add
}))
class UploadImg extends React.Component {
  state = {
    loading: false,
    imageUrl: `${localUrl}/public/static/ueditor/default.png`
  };
  componentDidMount() {}
  static getDerivedStateFromProps(nextProps, prevState) {
    // if(nextProps.add.articleData[0].data){
    //     return { imageUrl: nextProps.add.articleData[0].data }
    // }
    if (nextProps.img) {
      return { imageUrl: nextProps.img };
    }
    return null;
  }

  /**
   * 上传插件
   */
  fcUpload = key => {
    window.fc = new window.FcUpload({
      elem: "fcUpload",
      multiple: false, //是否允许上传多个文件
      type: "img", // 上传文件类型\ img 图片，  video 视频
      host:localUrl,
      actionImg: `${localUrl}/fcpublic/uploads/uploadImg`, //本地上传图片地址
      actionVideo: `${localUrl}/fcpublic/uploads/uploadVideo`, //本地上传视频地址
      callback: callRes => {
        let url;
        if (callRes.oss) {
          // oss 和本地返回数据结构不一样
          url = callRes.response[0];
        } else {
          url = callRes.response[0].data;
        }
        this.props.setUrl(url);
      }
    });
    window.fc.show();
  };

  render() {
    const imageUrl = this.state.imageUrl;
    return <img src={imageUrl} onClick={this.fcUpload} alt="avatar" width="144px" height="144px" />;
  }
}
export default UploadImg;
